<?php
namespace app\controller;

use app\HeadComponent;
use app\NavComponent;
use app\controller\Controller;
use app\repository\UserRepository;
use app\model\page;
use app\entity\Clazz;
use app\repository\ClazzRepository;
use app\service\ClazzService;
use app\service\TemplateService;
use app\component\pagination\PaginationComponent;

class ClazzController extends Controller {
    private $title = '欢迎使用';
    /**
     * 模板变量
     * */
    public $extracts = [];

    public function __construct() {
        if (!UserRepository::isLogin()) {
            header('Location: ./../login.view.php');
            die();
        }
    }

    public function add() {
        $this->title = '新增班级';
        // 权限判断
        $this->fetch();
    }


    /**
     * 模板传值
     * @param $key 关键字
     * @param $value 值
     * */
    private function assign($key, $value) {
        $this->extracts[$key] = $value;
    }

    public function edit() {
        $this->title = '编辑班级';
        if (!isset($_GET['id'])) {
            $this->error('未获取到 ID 参数');
        }

        $id = (int) $_GET['id'];
        $clazzService = new ClazzService;
        $clazz = $clazzService->getById($id);
        $this->assign('clazz', $clazz);
        $this->fetch('./../view/clazz/edit.html');
    }

    public function fetch($templateUrl = null) {
        // 根据调用的方法名，获取默认的模板名称
        if (is_null($templateUrl)) {
            $invokeMethods = debug_backtrace();
            $invokeMethod = $invokeMethods[1]['function'];
            $templateUrl = "./../view/clazz/$invokeMethod.html";
        }
       
        // 渲染结果放到模板变量中
        $this->assign('contentHtmls', TemplateService::render($templateUrl, $this->extracts)); 

        // 获取菜单的htmls
        $this->assign('navHtmls', NavComponent::render());

        echo TemplateService::render('./../view/clazz/fetch.html', $this->extracts);
    }

    public function index() {
        $this->title = '班级列表';
        $indexInput = new IndexInput($_GET);

        $clazzService =  new ClazzService();
        $page = $clazzService->page(
            $indexInput->page, 
            $indexInput->size,
            $indexInput->name,
            $indexInput->entranceDateBegin,
            $indexInput->entranceDateEnd,
            $indexInput->userName);
        $this->assign('indexInput', $indexInput);
        $this->assign('page', $page);
        $this->assign('paginationComponent', new PaginationComponent());
        $this->fetch();
    }

    public function notFound() {
        $this->fetch();
    }

    public function save() {
        $this->title = '保存';
        
        $clazz = new Clazz();
        $clazz->name = $_POST['name'];
        $clazz->entranceDate = $_POST['entranceDate'];
        $clazz->numberOfStudents = $_POST['numberOfStudents'];
        $clazz->user->id = $_POST['userId'];

        $clazzService = new ClazzService;
        $result = $clazzService->save($clazz);

        if ($result === true) {
            $this->success('操作成功', '');
        } else {
            $this->error('操作失败', $result);
        }
    }

    public function update() {
        $this->title = '更新班级';
        $updateInput = new UpdateInput($_POST);
        if ($updateInput->isError()) {
            $this->error('发生错误', $updateInput->getErrorMessage());
        }

        $clazzService = new ClazzService;
        $result = $clazzService->update($updateInput->id, 
            $updateInput->name,
            $updateInput->entranceDate,
            $updateInput->numberOfStudents,
            $updateInput->userId); 

        if ($result === true) {
            $this->success('操作成功', '');
        } else {
            $this->error('操作失败', $result);
        }
    }


    public function view() {
        $this->title = '查看班级';
        if (!isset($_GET['id'])) {
            $this->error('未获取到 ID 参数');
        }

        $id = (int) $_GET['id'];

        $clazzService = new ClazzService;
        $clazz = $clazzService->getById($id);

        $this->assign('clazz', $clazz);
        $this->fetch();
    }
}

/**
 * 对接index action输入
 * */
class IndexInput {
    public $page;
    public $size;
    public $name;
    public $entranceDateBegin;
    public $entranceDateEnd;
    public $userName;

    public function __construct($get) {
        $this->page = 0;
        $this->size = 10;
        if (isset($get['page'])) {
            $this->page = (int)$get['page'];
        }
        if (isset($get['size'])) {
            $this->size = (int)$get['size'];
        } 
        if (isset($get['name'])) {
            $this->name = $get['name'];
        }
        if (isset($get['entranceDateBegin'])) {
            $this->entranceDateBegin = $get['entranceDateBegin'];
        }
        if (isset($get['entranceDateEnd'])) {
            $this->entranceDateEnd = $get['entranceDateEnd'];
        }
        if (isset($get['userName'])) {
            $this->userName = $get['userName'];
        }
    }
}

class UpdateInput {
    public $id;
    public $name;
    public $entranceDate;
    public $numberOfStudents;
    public $userId;
    public $errorMessage;

    public function __construct($post) {
        $this->errorMessage = [];

        if (isset($post['id'])) {
            $this->id = (int)$post['id'];
        } else {
            array_push($this->errorMessage, '未传入id');
        }

        if (isset($post['name'])) {
            $this->name = $post['name'];
        } else {
            array_push($this->errorMessage, '未传入name');
        }

        if (isset($post['entranceDate'])) {
            $this->entranceDate = $post['entranceDate'];
        } else {
            array_push($this->errorMessage, '未传入entranceDate');
        }

        if (isset($post['numberOfStudents'])) {
            $this->numberOfStudents = $post['numberOfStudents'];
        } else {
            array_push($this->errorMessage, '未传入numberOfStudents');
        }

        if (isset($post['userId'])) {
            $this->userId = $post['userId'];
        } else {
            array_push($this->errorMessage, '未传入userId');
        }
    }

    public function isError() {
        return !empty($this->errorMessage);
    }

    public function getErrorMessage() {
        return implode($this->errorMessage, '、');
    }
}
